import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/Login.vue";
import Dashboard from "../views/Dashboard.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: (to) => {
      // 检查登录状态
      const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
      return isLoggedIn ? "/dashboard" : "/login";
    },
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/dashboard",
    name: "Dashboard",
    component: Dashboard,
    meta: { requiresAuth: true },
    children: [
      {
        path: "",
        redirect: "home",
      },
      {
        path: "home",
        name: "DashboardHome",
        component: () => import("../views/DashboardHome.vue"),
        meta: { requiresAuth: true },
      },
      {
        path: "test",
        name: "ComponentTest",
        component: () => import("../views/Test.vue"),
        meta: { requiresAuth: true },
      },
      // {
      //   path: "oss",
      //   name: "OssManagement",
      //   component: () => import("../views/OssPage.vue"),
      //   meta: { requiresAuth: true },
      // },
    ],
  },
];

const router = new VueRouter({
  mode: "hash",
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log("路由守卫触发:", { to: to.path, from: from.path });

  const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
  console.log("登录状态:", isLoggedIn);

  // 检查需要认证的路由
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!isLoggedIn) {
      console.log("需要认证但未登录，重定向到login");
      next("/login");
    } else {
      console.log("已认证，允许访问");
      next();
    }
  } else {
    // 如果已登录用户访问登录页面，重定向到dashboard
    if (to.path === "/login" && isLoggedIn) {
      console.log("已登录用户访问login页面，重定向到dashboard");
      next("/dashboard");
    } else {
      console.log("允许访问");
      next();
    }
  }
});

export default router;
